import React, { useState, useEffect, useRef } from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { Menu, Form, Button, Dropdown, message,Switch,Table, Card, Tabs,Row,Col,Popconfirm, Divider } from 'antd';
import styles from './style.less';
import { FormComponentProps } from 'antd/lib/form';
import { formatMessage } from 'umi-plugin-react/locale';
import { bdExec } from '@/helpers/RequestHelper';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { DownOutlined, PlusCircleOutlined,CheckOutlined, CheckCircleTwoTone, MinusOutlined } from '@ant-design/icons';
import moment from 'moment';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { FormValueType } from './components/ConfigForm';
import ConfigForm from './components/ConfigForm';
import DataForm from './components/DataForm';
import DataGroup from './components/DataGroup';
import { addRule, updateRule, moveRule,removeRule, queryRule, queryListRule } from './service';
import * as tsxHelper from '@/helpers/TsxHelper';
import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import { EditableFormRow, EditableCell } from './components/BDEditable';
const { Item } = Menu;
const { TabPane } = Tabs;
interface ConfigListProps extends FormComponentProps { }

const handleAdd = async (fields: FormValueType) => {
    return bdExec({ fn: addRule, args: fields, successMsg: '添加成功', failMsg: '添加失败请重试！' });
};

const handleUpdate = async (fields: FormValueType) => {
    return bdExec({ fn: updateRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};
const handleMove = async (fields: FormValueType) => {
    return bdExec({ fn: moveRule, args: fields, successMsg: '移动成功', failMsg: '移动失败请重试！' });
};

const handleRemove = async (selectedRows: any[]) => {
    if (!selectedRows) return true;
    const ids: any = selectedRows.map(row => row.id).toString();
    return bdExec({ fn: removeRule, args: { ids }, successMsg: '删除成功，即将刷新', failMsg: '删除失败，请重试！', hasLoading: false });
};

const ConfigList: React.FC<ConfigListProps> = (props) => {

    let main: HTMLDivElement | undefined | any = undefined;
    const actionRef = useRef<ActionType>();
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [stepFormValues, setStepFormValues] = useState({});
    const [selectIndex, setSelectIndex] = useState<any>();
    const [groupId, setgroupId] = useState<string>('');
    const [mode, setMode] = useState<any>('inline');
    const [rowKeys, setRowKeys] = useState<string[] | number[]>([]);
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    const [isUpdate1, setIsUpdate1] = useState<boolean>(false);
    const [radioType, setRadioType] = useState<string | 'string' | 'switch' | 'date' | 'file' | 'color'>('string');
    const [picture, setPicture] = useState<any[]>([]);
    const [color, setColor] = useState<string>('#1890ff');
    const [stateData, setStateData] = useState<any>({ common: {} });
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    const [radioType1, setRadioType1] = useState<any>()
    const [all, setAll] = useState<any>();
     //列表数据
     const [dataList,setDataList] = useState<any>([]);

     //多语言列表数据
     const [langList, setLangList] = useState<any>([]);
    // 表单可见 关键变量
    const handleChange = (value: any) => {
        setRadioType1(value)
    }
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    const [dataModalVisible1, handleDataModalVisible1] = useState<boolean>(false);
    const [dataModalVisible2, handleDataModalVisible2] = useState<boolean>(false);
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    const [common, setcommon] = useState<any>();
    const [moveId, setMoveId] = useState();

    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({common:{}});
    
    const [dataFormValues1, setDataFormValues1] = useState({});
    useEffect(() => {
        window.addEventListener('resize', resize);
        resize();
        initListData();
        return () => window.removeEventListener('resize', resize);
    }, []);
    const buildEnum = (option: any) => {
        let defaultEnum = {all: { text: '全部' } };
        option?.map((val: any, index: number) => {
            defaultEnum[parseInt(val.key)] = { text: val.text };
        });
       // defaultEnum['all'] = { text: '全部' }
        
        console.log(444,defaultEnum)
        return defaultEnum;
    }
    const [nameList, setnameList] = useState<any>([]);
    const handleName = (val) => {
        setnameList(val)
    }
    
    const getNameByType = (key:any,options:any[]) => {
        let name = "-";
        if(options && options.length>0){
            options.map(item=>{
                if(item.key == key){
                    if(item.name){
                        name = item.name;
                    }else{
                        name = item.text;
                    }
                }
            })
        }
        return name
    }
    const columns = [
        {
            title: '所属分类',
            dataIndex: 'parent_id',
            render: (text:any,record:any) => (<span>{getNameByType(text,apiState.common?.oneGroupOption)}</span>),
            width: 150,
        },
        {
            title: '小组名称',
            dataIndex: 'name',
        },
        {
            title: '小组模式',
            dataIndex: 'type_mode',
           render: (text:any,record:any) => (<span>{getNameByType(text,apiState.common?.typeFind)}</span>)
        },
        {
            title: '关注方式',
            dataIndex: 'type_follow',
            //valueEnum: followEnum,
            render: (text:any,record:any) => (<span>{getNameByType(text,apiState.common?.typeFollow)}</span>)
        },
        {
            title: '小组管理员',
            dataIndex: 'admin_members',
            hideInSearch: true,
            render: (text:any,record:any) => (<span>{getNameByType(text,apiState.common?.memberOption)}</span>)
        },
        {
            title: '发布权限',
            dataIndex: 'publish_post',
            render: (text:any,record:any) => (<span>{getNameByType(text,apiState.common?.publishPostOption)}</span>)
        },
        {
            title: '评论权限',
            dataIndex: 'publish_comment',
            hideInSearch: true,
            render: (text:any,record:any) => (<span>{getNameByType(text,apiState.common?.publishPostOption)}</span>)
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            width:300,
            render: (_: any, record: React.SetStateAction<any>) => (
                <>
                <Popconfirm
                  title="确认恢复吗"
                  onConfirm={()=>{recoverStop(record)}}
                  onCancel={()=>{}}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button type="primary" onClick={()=>{
                      
                  }}>恢复</Button>
                </Popconfirm>
                {/* <Button type="default" style={{marginLeft: 10, marginRight: 10,}} onClick={() => {
                            handleDataModalVisible2(true);
                            setMoveId(record.id);
                        }}>移动</Button>
                <Button type="danger"  style={{marginLeft: 10, marginRight: 10,}}  onClick={async () => {
                        let s = await handleUpdateItem({ id: record.id, is_enable: (!record.is_enable).toString() });
                        s && initListData({id:groupId});
                    }}>{record.is_enable == true ? '停用':'启用'}</Button> */}
                  
                </>
            ),
        },
    ];

    //恢复
    const recoverStop = (params?: any) => {
        const args: any = {is_enable: true};
        //args.parent_id = selectIndex;
        // console.log(43,selectIndex)
        // params && params.name && (args.name = params.name);
        params && params.id && (args.id = params.id);
        console.log('....1111')
        return bdExec({
            fn: updateRule,
            args,
            failMsg: '请求数据失败',
            hasCallBack: true,
            hasLoading: false,
        }).then((res: any) => {
            if (res.execStatus) {
                // setLangList(res.data.data);
                // setApiState(res.data);
                // console.log(24,res.data.data);
                // return res.data.listData;
                initListData();
            }
        })
    }

    const handleSave = (row:any) => {
        const newData = [...langList];
        const index = newData.findIndex(item => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        })
        setLangList(newData);
        updateRule({id: row.id,rank_num: row.rank_num}).then(res=>{
            if(res.code == 0){
                // message.success('修改成功');
            }
        })
    };
    const newcolumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave: (row: any) => handleSave(row),
            }),
        };
    });
    // const initData = (isTrue?: any) => {
    //     const args: any = {};
    //     console.log('....1111')

    //     args.type = 2;
    //     args.is_enable = 0;
    //     // args.config_group_id = 5
    //     return bdExec({
    //         fn: queryRule,
    //         args,
    //         failMsg: '请求数据失败',
    //         hasCallBack: true,
    //         hasLoading: false,
    //     }).then((res: any) => {
    //         if (res.execStatus) {
    //             setStateData(res.data)
    //             setcommon(res.data.common)
    //             console.log(res.data.data[0].id, 5552)
    //              setgroupId(res.data.data[0].id)
    //              setDataFormValues(res.data.data[0]);
    //             if (!isTrue) {
    //                 setSelectIndex(res.data.data[0].id.toString());
    //                 initListData({id:res.data.data[0].id})
    //             }
            
    //             return res.data.listData;
    //         }
    //     })
    // }
    const initListData = (params?: any) => {
        const args: any = {type: 2, is_enable: 0};
        //args.parent_id = selectIndex;
        // console.log(43,selectIndex)
        // params && params.name && (args.name = params.name);
        // params && params.id && (args.parentId = params.id);
        console.log('....1111')
        return bdExec({
            fn: queryRule,
            args,
            failMsg: '请求数据失败',
            hasCallBack: true,
            hasLoading: false,
        }).then((res: any) => {
            if (res.execStatus) {
                setLangList(res.data.data);
                setApiState(res.data);
                console.log(24,res.data.data);
                return res.data.listData;
            }
        })
    }

    const initValuesData = (record: any) => {
        setIsUpdate1(true);
        setDataFormValues1(record);
      console.log(32,record)
    }

    const getMenu = () => {
        const menuMap = stateData.data || [];
        return menuMap.map((item: any) => <Item style={{display:'flex',justifyContent:'space-between'}} key={`${item.id}`}>{item.name}  
        <div>
            <a
                onClick={(e) => {
                    e.stopPropagation();
                    console.log(item);
                    handleDataModalVisible(true);
                    setIsUpdate(true);
                    setDataFormValues(item);
                }}
            >
            编辑</a>
            {/* <Divider type="vertical"/>
            <Popconfirm
              title="确认删除小组吗"
              onConfirm={()=>{}}
              onCancel={()=>{}}
              okText="确认"
              cancelText="取消"
            >
              <a onClick={(e)=>{
                  e.stopPropagation();
              }}>删除</a>
            </Popconfirm> */}
        </div>
        
        
        </Item>);
    };




    const resize = () => {
        if (!main) {
            return;
        }
        requestAnimationFrame(() => {
            if (!main) {
                return;
            }
            let mode: 'inline' | 'horizontal' = 'inline';
            const { offsetWidth } = main;
            if (main.offsetWidth < 641 && offsetWidth > 400) {
                mode = 'horizontal';
            }
            if (window.innerWidth < 768 && offsetWidth > 400) {
                mode = 'horizontal';
            }
            setMode(mode);
        });
    };

    // 表单提交
    const handleSubmitDataForm1 = (value: any) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then(status => {
            console.log("handleSubmitDataForm status is ", status)
            if (status) {
                handleDataModalVisible1(false)
                setIsUpdate1(false)
                setDataFormValues1({})
                initData(true);
                initListData({id:groupId})
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }
    const handleSubmitDataForm2 = (value: any) => {
        return new Promise((resolve, reject) => {
            let s =  handleMove(value);
            resolve(s);
        }).then(status => {
            console.log("handleSubmitDataForm status is ", status)
            if (status) {
                handleDataModalVisible2(false)
                initListData({id:groupId})
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }
    const handleSetPicture = (value: any) => {
        setPicture(value)
    }
    const handleSubmit = async () => {
        setPicture([])
        handleModalVisible(false)
        await initData(true);
        if (actionRef.current) {
            actionRef.current.reload();
        }
    }

    // console.log('update-->selectIndex-->', selectIndex)
    return (
        <Card>
            <GridContent>
                <div className={styles.right}>
                     {/* <Row style={{backgroundColor: "#fff",padding:"15px 25px",marginBottom:10,}}>
                        <Col style={{display: "flex",justifyContent:"space-between",alignItems:"center"}}>
                            <div>
                                <Button type="primary" style={{marginRight: 10}} onClick={()=>{setIsUpdate1(false); handleDataModalVisible1(true);}}>新建小组</Button> 
                            </div> 
                        </Col>    
                    </Row> */}
                    <Table
                        style={{ backgroundColor: "#fff" }}
                        components={{
                            body: {
                                row: EditableFormRow,
                                cell: EditableCell,
                            },
                        }}
                        rowClassName={() => 'editable-row'}
                        columns={newcolumns}
                        dataSource={langList}
                        pagination={false}
                    />
                   
                    {
                        previewModelVisible && (
                            <PreviewForm
                                previewModelVisible={previewModelVisible}
                                onVisibleModel={handlePreviewModalVisible}
                                previewImg={previewImg}
                            />
                        )
                    }
                </div>
            </GridContent>
            <DataGroup
                dataModalVisible={dataModalVisible1}
                dataFormValues={dataFormValues1}
                isUpdate={isUpdate1}
                common={common}
                onSubmit={ async formValue => handleSubmitDataForm1(formValue) }
                onCancel={() => handleDataModalVisible1(false)}
            />
        </Card>
    );
}
const handleUpdateItem = async (fields: FormValueType) => {
    return RequestHelper.bdExec({ fn: updateRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};

export default Form.create<ConfigListProps>()(ConfigList);

